package br.com.async.core.application.impl;

import java.util.List;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.com.async.core.application.EnterpriseApplication;
import br.com.async.core.domain.enterprise.Enterprise;
import br.com.async.core.domain.enterprise.EnterpriseRepository;
import br.com.async.core.domain.user.User;
import br.com.async.core.domain.user.UserRepository;
import br.com.async.core.util.Encrypt;
@Transactional (propagation= Propagation.REQUIRED)
public class EnterpriseApplicationImpl implements EnterpriseApplication{
	
	private EnterpriseRepository enterpriseRepository;
	private UserRepository userRepository;
	
	public EnterpriseApplicationImpl(EnterpriseRepository enterpriseRepository, UserRepository userRepository){
		super();
		this.enterpriseRepository = enterpriseRepository;
		this.userRepository = userRepository;
	}
	
	@Override
	public void save(Enterprise entity) {
		try {
			enterpriseRepository.save(entity);
			userRepository.save(new User(
					entity.getPerson().getContact().getEmail(), Encrypt.md5(entity.getPerson().getContact().getEmail()+" "+entity.getCnpj()), entity.getPerson()));
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void update(Enterprise entity) {
		enterpriseRepository.update(entity);
		
	}

	@Override
	public void disable(Enterprise entity) {
		enterpriseRepository.disable(entity);
		
	}

	@Override
	public Enterprise findById(Integer code) {
		return enterpriseRepository.findById(code);
	}

	@Override
	public List<Enterprise> list() {
		return enterpriseRepository.list();
	}

	@Override
	public Enterprise findByUrl(String url) {
		return enterpriseRepository.findByUrl(url);
	}

}
